# -*- coding: utf-8 -*-

import arcpy

topdldm = """
def topdldm(aa):
    if aa[0] != "2":
        cc = aa[0]
    else:
        cc = aa
    return cc"""

disdldm = """
def disdldm(JOIN_DLDM, JOIN_DIS , DisNO, DLDM):
    i = 1
    CATCH = 0
    for j in JOIN_DLDM.split(',')[1:]:
        if DLDM == j:
            DisNO = JOIN_DIS.split(',')[i]
            CATCH = 1
            break
        i += 1
    if CATCH == 0:
        i = 1
        for j in JOIN_DLDM.split(',')[1:]:
            if ( (DLDM[0] == j[0]) and (DLDM[0] != '2')):
                DisNO = JOIN_DIS.split(',')[i]
                CATCH = 1
                break
            i += 1  

    return DisNO"""
workspace = arcpy.GetParameterAsText(0)
ori = "ORI"
singlepart = "SINGLEPART"
more_then_400 = "more_then_400"
less_then_400 = "less_then_400"
dissolve_less_than_400 = "dissolve_less_than_400"
dissolve_less_than_400_2st = "dissolve_less_than_400_2st"
dissolve_less_than_400_2st_spatial_join = "dissolve_less_than_400_2st_spatial_join"
target = "final"
ALL_MERGE = "all_merge"
result = 'result'
result_layer = 'result_lyr'
Eliminate_layer = 'Eliminate_lyr'
Eliminate_layer1 = 'Eliminate_lyr1'
Eliminate_layer2 = 'Eliminate_lyr2'
Eliminate = "Eliminate"
Eliminate1 = "Eliminate1"
Eliminate2 = "Eliminate2"
Eliminate3 = "转手工检查结果"
arcpy.env.workspace = workspace
arcpy.env.overwriteOutput = True
list_Feature = arcpy.ListFeatureClasses()
for each in list_Feature:
    if each != "ORI":
        arcpy.Delete_management(each)
        arcpy.AddMessage ("删除图层%s".decode("utf-8") % each)
try:
    # 将ORI原始图层的多部件要素转为单部件要素
    arcpy.MultipartToSinglepart_management(ori, singlepart)
    # 为SINGLEPART图层添加唯一值字段DisNO
    arcpy.AddMessage ("添加唯一值字段".decode("utf-8"))
    arcpy.AddField_management(singlepart, "DisNO", "TEXT", "", "", "20", "", "NULLABLE", "NON_REQUIRED", "")
    # 为SINGLEPART图层添加面积字段MJ
    arcpy.AddMessage ("添加面积字段".decode("utf-8"))
    arcpy.AddField_management(singlepart, "MJ", "DOUBLE", "", "", "20", "", "NULLABLE", "NON_REQUIRED", "")
    # 为SINGLEPART图层计算唯一值
    arcpy.AddMessage ("计算唯一值".decode("utf-8"))
    arcpy.CalculateField_management(singlepart, "DisNO", "!OBJECTID!", "PYTHON_9.3")
    # 为SINGLEPART图层计算面积
    arcpy.AddMessage ("计算面积".decode("utf-8"))
    arcpy.CalculateField_management(singlepart, "MJ", "!shape.area!", "PYTHON_9.3")
    # 导出SINGLEPART图层中面积小于400的面到less_then_400图层
    arcpy.AddMessage ("导出面积小于400的面".decode("utf-8"))
    arcpy.Select_analysis(singlepart, less_then_400, 'MJ <  400')
    # 导出SINGLEPART图层中面积大于等于400的面到more_then_400
    arcpy.AddMessage ("导出面积大于400的面".decode("utf-8"))
    arcpy.Select_analysis(singlepart, more_then_400, 'MJ >=  400')
    # 融合less_then_400图层中坐落代码一致且地类代码一致的相邻要素，输出为dissolve_less_than_400,输出字段ZLDWDM,GHDLDM,GHDLMC,DisNO
    arcpy.AddMessage ("融合面积小于400面中坐落代码一致且地类代码一致的相邻要素".decode("utf-8"))
    arcpy.Dissolve_management(less_then_400, dissolve_less_than_400, "ZLDWDM;GHDLDM", "GHDLMC LAST;DisNO LAST",
                              "SINGLE_PART",
                              "DISSOLVE_LINES")
    # 修改dissolve_less_than_400图层字段LAST_GHDLMC为GHDLMC
    arcpy.AddMessage ("修改字段名为GHDLMC".decode("utf-8"))
    arcpy.AlterField_management(dissolve_less_than_400, "LAST_GHDLMC", "GHDLMC", "", "", "", "NON_NULLABLE", "false")
    # 修改dissolve_less_than_400图层字段LAST_DisNO为DisNO
    arcpy.AddMessage ("修改字段名为DisNO".decode("utf-8"))
    arcpy.AlterField_management(dissolve_less_than_400, "LAST_DisNO", "DisNO", "", "", "", "NON_NULLABLE", "false")
    # 为dissolve_less_than_400图层添加面积字段MJ
    arcpy.AddMessage ("添加面积字段".decode("utf-8"))
    arcpy.AddField_management(dissolve_less_than_400, "MJ", "DOUBLE", "", "", "20", "", "NULLABLE", "NON_REQUIRED", "")
    # 计算面积
    arcpy.AddMessage ("计算面积".decode("utf-8"))
    arcpy.CalculateField_management(dissolve_less_than_400, "MJ", "!shape.area!", "PYTHON_9.3")
    # 添加一级地类字段TOPDL
    arcpy.AddMessage ("添加一级地类字段".decode("utf-8"))
    arcpy.AddField_management(dissolve_less_than_400, "TOPDL", "TEXT", "", "", "20", "", "NULLABLE", "NON_REQUIRED", "")
    # 计算一级地类
    arcpy.AddMessage ("计算一级地类".decode("utf-8"))
    arcpy.CalculateField_management(dissolve_less_than_400, "TOPDL", "topdldm( !GHDLDM! )", "PYTHON_9.3",
                                    topdldm)
    # 融合一级地类一致的面
    arcpy.AddMessage ("融合一级地类一致的面".decode("utf-8"))
    arcpy.Dissolve_management(dissolve_less_than_400, dissolve_less_than_400_2st, "ZLDWDM;TOPDL",
                              "GHDLMC FIRST;DisNO FIRST;GHDLDM FIRST", "SINGLE_PART", "DISSOLVE_LINES")
    #
    # # 为SINGLEPART图层计算唯一值
    # arcpy.AddMessage ("计算唯一值".decode("utf-8") )
    # arcpy.CalculateField_management(dissolve_less_than_400_2st, "FIRST_DisNO", "int(!OBJECTID!)+120000", "PYTHON_9.3")
    arcpy.AddMessage ("小面与大面空间连接".decode("utf-8"))

    arcpy.SpatialJoin_analysis(dissolve_less_than_400_2st, more_then_400, dissolve_less_than_400_2st_spatial_join,
                               "JOIN_ONE_TO_ONE", "KEEP_ALL",
                               "ZLDWDM \"ZLDWDM\" true true false 19 Text 0 0 ,First,#,dissolve_less_than_400_2st,ZLDWDM,-1,-1;DisNO \"DisNO\" true true false 20 Text 0 0 ,First,#,dissolve_less_than_400_2st,FIRST_DisNO,-1,-1;GHDLDM \"GHDLDM\" true true false 20 Text 0 0 ,First,#,dissolve_less_than_400_2st,FIRST_GHDLDM,-1,-1;TOPDL \"TOPDL\" true true false 20 Text 0 0 ,First,#,dissolve_less_than_400_2st,TOPDL,-1,-1;GHDLMC \"GHDLMC\" true true false 50 Text 0 0 ,First,#,dissolve_less_than_400_2st,FIRST_GHDLMC,-1,-1;JOIN_DLDM \"JOIN_DLDM\" true true false 255 Text 0 0 ,Join,\",\",dissolve_less_than_400_2st,FIRST_GHDLDM,-1,-1,more_then_400,GHDLDM,-1,-1;JOIN_DIS \"JOIN_DIS\" true true false 255 Text 0 0 ,Join,\",\",dissolve_less_than_400_2st,FIRST_DisNO,-1,-1,more_then_400,DisNO,-1,-1",
                               "INTERSECT", "", "")
    arcpy.AddMessage ("计算空间连接值".decode("utf-8"))
    # Process: Calculate Field
    arcpy.CalculateField_management(dissolve_less_than_400_2st_spatial_join, "DisNO",
                                    "disdldm( !JOIN_DLDM! , !JOIN_DIS! , !DisNO!, !GHDLDM! )", "PYTHON_9.3",
                                    disdldm)
    ##  Process: 合并
    arcpy.AddMessage ("合并全部面".decode("utf-8"))
    arcpy.Merge_management("dissolve_less_than_400_2st_spatial_join;more_then_400", ALL_MERGE,
                           "Join_Count \"Join_Count\" true true false 4 Long 0 0 ,First,#,dissolve_less_than_400_2st_spatial_join,Join_Count,-1,-1;TARGET_FID \"TARGET_FID\" true true false 4 Long 0 0 ,First,#,dissolve_less_than_400_2st_spatial_join,TARGET_FID,-1,-1;ZLDWDM \"ZLDWDM\" true true false 19 Text 0 0 ,First,#,dissolve_less_than_400_2st_spatial_join,ZLDWDM,-1,-1,more_then_400,ZLDWDM,-1,-1;DisNO \"DisNO\" true true false 20 Text 0 0 ,First,#,dissolve_less_than_400_2st_spatial_join,DisNO,-1,-1,more_then_400,DisNO,-1,-1;GHDLDM \"GHDLDM\" true true false 20 Text 0 0 ,First,#,dissolve_less_than_400_2st_spatial_join,GHDLDM,-1,-1,more_then_400,GHDLDM,-1,-1;TOPDL \"TOPDL\" true true false 20 Text 0 0 ,First,#,dissolve_less_than_400_2st_spatial_join,TOPDL,-1,-1;GHDLMC \"GHDLMC\" true true false 50 Text 0 0 ,First,#,dissolve_less_than_400_2st_spatial_join,GHDLMC,-1,-1,more_then_400,GHDLMC,-1,-1;JOIN_DLDM \"JOIN_DLDM\" true true false 255 Text 0 0 ,First,#,dissolve_less_than_400_2st_spatial_join,JOIN_DLDM,-1,-1;JOIN_DIS \"JOIN_DIS\" true true false 255 Text 0 0 ,First,#,dissolve_less_than_400_2st_spatial_join,JOIN_DIS,-1,-1;Shape_Length \"Shape_Length\" false true true 8 Double 0 0 ,First,#,dissolve_less_than_400_2st_spatial_join,Shape_Length,-1,-1,more_then_400,Shape_Length,-1,-1;Shape_Area \"Shape_Area\" false true true 8 Double 0 0 ,First,#,dissolve_less_than_400_2st_spatial_join,Shape_Area,-1,-1,more_then_400,Shape_Area,-1,-1")

    # Process: 融合
    arcpy.AddMessage ("融合小图斑".decode("utf-8"))
    arcpy.Dissolve_management(ALL_MERGE, result, "ZLDWDM;DisNO", "GHDLDM FIRST;GHDLMC FIRST", "SINGLE_PART",
                              "DISSOLVE_LINES")
    #为result图层添加长度面积比字段
    arcpy.AddMessage ("添加长度面积比字段".decode("utf-8"))
    arcpy.AddField_management(result, "长度面积比", "DOUBLE", "", "", "20", "", "NULLABLE", "NON_REQUIRED", "")

    # 为result图层计算长度面积比
    arcpy.AddMessage ("计算长度面积比".decode("utf-8"))
    arcpy.CalculateField_management(result, "长度面积比", "!shape.length@meter!/!shape.area!", "PYTHON_9.3")
    arcpy.AddMessage ("创建结果图层".decode("utf-8"))
    arcpy.MakeFeatureLayer_management(result, result_layer)
    # Process: 按属性选择图层
    arcpy.AddMessage ("选择面积小于400的非建设用地".decode("utf-8"))
    arcpy.SelectLayerByAttribute_management(result_layer, "NEW_SELECTION",
                                            "(SUBSTRING( FIRST_GHDLDM,1,1) = '1' or SUBSTRING( FIRST_GHDLDM,1,1) = '3') and Shape_Area <400")

    # Process: 消除
    arcpy.AddMessage ("消除面积小于400的非建设用地到非建设用地，周边都是建设用地和基本农田的不消除".decode("utf-8"))
    arcpy.Eliminate_management(result_layer, Eliminate, "LENGTH", "FIRST_GHDLDM = '4' or substring(FIRST_GHDLDM,1,1) = '2'",
                               "")
    arcpy.AddMessage ("创建消除图层".decode("utf-8"))
    arcpy.MakeFeatureLayer_management(Eliminate, Eliminate_layer)
    arcpy.AddMessage ("选择面积小于400的非建设用地".decode("utf-8"))
    arcpy.SelectLayerByAttribute_management(Eliminate_layer, "NEW_SELECTION",
                                            "(SUBSTRING( FIRST_GHDLDM,1,1) = '1' or SUBSTRING( FIRST_GHDLDM,1,1) = '3') and Shape_Area <400")

    # Process: 消除
    arcpy.AddMessage ("消除面积小于400的非建设用地到建设用地，周边都是基本农田的不消除".decode("utf-8"))
    arcpy.Eliminate_management(Eliminate_layer, Eliminate1, "LENGTH", "FIRST_GHDLDM = '4'", "")
    arcpy.AddMessage ("创建消除图层1".decode("utf-8"))
    arcpy.MakeFeatureLayer_management(Eliminate1, Eliminate_layer1)
    # Process: 按属性选择图层 (2)
    arcpy.AddMessage ("选择面积小于10的建设用地".decode("utf-8"))
    arcpy.SelectLayerByAttribute_management(Eliminate_layer1, "NEW_SELECTION",
                                            "Shape_Area < 10 and substring(FIRST_GHDLDM,1,1) = '2'")
    arcpy.AddMessage ("消除面积小于10平米的建设用地到建设用地，周边都是非建设用地和基本农田的不消除".decode("utf-8"))
    # Process: 消除 (2)
    arcpy.Eliminate_management(Eliminate_layer1, Eliminate2, "LENGTH",
                               "FIRST_GHDLDM = '4' and substring(FIRST_GHDLDM,1,1) <> '2'", "")
    arcpy.AddMessage ("创建消除图层2".decode("utf-8"))
    arcpy.MakeFeatureLayer_management(Eliminate2, Eliminate_layer2)
    arcpy.AddMessage ("选择面积小于10的建设用地".decode("utf-8"))
    arcpy.SelectLayerByAttribute_management(Eliminate_layer2, "NEW_SELECTION",
                                            "Shape_Area < 10 and substring(FIRST_GHDLDM,1,1) = '2'")
    arcpy.AddMessage ("消除面积小于10平米的建设用地到非建设用地，周边都是基本农田的不消除".decode("utf-8"))
    # Process: 消除 (2)
    arcpy.Eliminate_management(Eliminate_layer2, Eliminate3, "LENGTH", "FIRST_GHDLDM = '4' ", "")
except:
    arcpy.AddMessage("软件错误，请将数据发送至13848195@qq.com查找故障原因！")